import base64, pickle

from django_redis import get_redis_connection


def marge_carts_cookie_redis(request, response, user):
    """合并购物车"""
    # 获取cookie购物车里的数据
    cart_str = request.COOKIES.get('carts')
    # 判断购物车里是否有数据
    if not cart_str:
        return response
    cookie_cart_dict = pickle.loads(base64.b64decode((cart_str.encode())))
    # 准备的新的数据容器　用来保存 sku_id  count  selected
    new_cart_dict = {}
    new_selected_add = []
    new_selected_rem = []
    # 遍历出cookie购物车里的数据
    for sku_id, cookie_dict in cookie_cart_dict.items():
        # 错误的数据结构
        # new_cart_dict[sku_id] = {
        #     'count': cookie_dict['count']
        # }
        # 正确的数组结构
        new_cart_dict[sku_id] = cookie_dict['count']
        if cookie_dict['selected']:
            new_selected_add.append(sku_id)
        else:
            new_selected_rem.append(sku_id)

    # 根据新的数据结构　合并到redis数据库
    redis_coon = get_redis_connection('carts')
    pl = redis_coon.pipeline()
    pl.hmset('carts_%s' % user.id, new_cart_dict)
    if new_selected_add:
        pl.sadd("selected_%s" % user.id, *new_selected_add)
    if new_selected_rem:
        pl.srem("selected_%s" % user.id, *new_selected_rem)
    pl.execute()

    response.delete_cookie('carts')
    return response